package org.ehe.finance.payable.publisher;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.finance.payable.event.DueReminderEvent;
import org.ehe.finance.payable.event.PayableCreatedEvent;
import org.ehe.finance.payable.event.PaymentMadeEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;

/**
 * 事件发布
 * @author :zhangnn
 * @className :PayableEventPublisher
 * @description: TODO
 * @date 2025-09-02 10:43:10
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PayableEventPublisher {
    private final ApplicationEventPublisher eventPublisher;

    /**
     * 发布应付账款创建事件
     */
    public void publishPayableCreated(Long payableId, String billNo, Long supplierId, BigDecimal amount) {
        try {
            PayableCreatedEvent event = new PayableCreatedEvent(this, payableId, billNo, supplierId, amount);
            eventPublisher.publishEvent(event);
            log.info("发布应付账款创建事件成功 - 单据号: {}, 供应商ID: {}, 金额: {}",
                billNo, supplierId, amount);
        } catch (Exception e) {
            log.error("发布应付账款创建事件失败 - 单据号: {}", billNo, e);
        }
    }

    /**
     * 发布应付账款付款事件
     */
    public void publishPaymentMade(Long payableId, String billNo, BigDecimal paymentAmount, BigDecimal remainingAmount) {
        try {
            PaymentMadeEvent event = new PaymentMadeEvent(this, payableId, billNo, paymentAmount, remainingAmount);
            eventPublisher.publishEvent(event);
            log.info("发布付款事件成功 - 单据号: {}, 付款金额: {}, 剩余金额: {}",
                billNo, paymentAmount, remainingAmount);
        } catch (Exception e) {
            log.error("发布付款事件失败 - 单据号: {}", billNo, e);
        }
    }

    /**
     * 发布应付账款到期提醒事件
     */
    public void publishDueReminder(Long payableId, String billNo, Long supplierId,
                                   LocalDate dueDate, BigDecimal unpaidAmount) {
        try {
            DueReminderEvent event = new DueReminderEvent(this, payableId, billNo, supplierId, dueDate, unpaidAmount);
            eventPublisher.publishEvent(event);
            log.info("发布到期提醒事件成功 - 单据号: {}, 到期日期: {}, 未付金额: {}",
                billNo, dueDate, unpaidAmount);
        } catch (Exception e) {
            log.error("发布到期提醒事件失败 - 单据号: {}", billNo, e);
        }
    }
}
